<template>
  <div style="">
    <el-form ref="formData" :rules="rules" :model="temp" label-position="left" label-width="150px" style="margin-left:50px;margin-right:50px;">
      <el-form-item label="头像" prop="Avatar">
        <el-upload
          class="avatar-uploader"
          action="#"
          :http-request="upload"
          :show-file-list="false"
          accept="image/*"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="temp.Avatar" :src="temp.Avatar" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
      <el-form-item label="群组名称" prop="GroupName">
        <el-input v-model.trim="temp.GroupName" placeholder="请输入群组名称" clearable />
      </el-form-item>
      <el-form-item label="群组类型" prop="GroupType">
        <el-radio v-model="temp.GroupType" label="Private">支持，同新版本中的 Work（好友工作群）</el-radio>
        <el-radio v-model="temp.GroupType" label="Public">陌生人社交群(私有群)</el-radio>
        <el-radio v-model="temp.GroupType" label="ChatRoom">支持，同新版本中的 Meeting（临时会议群） </el-radio>
        <el-radio v-model="temp.GroupType" label="AVChatRoom">直播群</el-radio>
        <el-radio v-model="temp.GroupType" label="Community">（社群） 支持</el-radio>
      </el-form-item>
      <el-form-item label="群组公告" prop="Announcement">
        <el-input
          v-model.trim="temp.Announcement"
          placeholder="请输入群组公告"
          type="textarea"
          rows="5"
        />
      </el-form-item>
      <el-form-item label="群组简介" prop="GroupIntroduction">
        <el-input
          v-model.trim="temp.GroupIntroduction"
          placeholder="请输入群组简介"
          type="textarea"
          rows="5"
        />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer" style="text-align: center;">
      <el-button @click="cancel">
        取消
      </el-button>
      <el-button type="primary" :loading="loading" @click="createData()">
        确认
      </el-button>
    </div>
  </div>
</template>

<script>
import { validateGroupName } from '@/utils/validator'
import dayjs from 'dayjs'
import { GetGroupByGroupID } from '@/api/Group'
import { UploadFile } from '@/api/File'
import { TipsBox } from '@/utils/feedback'

export default {
  name: 'DataForm',
  props: {
    operationType: { type: String, default: '' },
    loading: { type: Boolean, default: false },
    editData: { type: Object, default: null }
  },
  data() {
    return {
      temp: {
        GroupId: '',
        GroupType: 'Private',
        UserId: '',
        GroupName: '',
        Avatar: '',
        GroupIntroduction: '',
        Announcement: ''
      },
      rules: {
        GroupName: [{ required: true, trigger: 'blur', validator: validateGroupName }]
      },
      imageUrl: ''
    }
  },
  watch: {
    // 监听对象
    operationType: {
      handler(newVal) {
        this.operationType = newVal
        this.getFormType() // 好像没走这个方法
      },
      deep: true
    }
  },
  mounted() {
    this.getFormType()
  },
  methods: {
    cancel() {
      this.$emit('dialogFormVisibleEmit', false)
    },
    getFormType() {
      if (this.operationType === 'edit') {
        GetGroupByGroupID(`groupId=${this.editData.GroupId}`).then(res => {
          if (res.statusCode === 200) {
            Object.keys(this.temp).map(key => res.data[0][key] && (this.temp[key] = res.data[0][key]))
          }
        })
      } else if (this.operationType === 'add') {
        // 清空表单
        this.$refs['formData'].resetFields()
      }
    },
    //
    createData() {
      // return
      this.$refs['formData'].validate((valid) => {
        if (valid) {
          if (this.temp.BirthDay) {
            this.temp.BirthDay = dayjs(this.temp.BirthDay).format('YYYY-MM-DD')
          }
          this.$emit('createDataEmit', this.temp)
        }
      })
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type.includes('image')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('只能上传图片!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    upload(file) {
      const formData = new FormData()
      formData.append('file', file.file)
      UploadFile(formData).then(res => {
        let type = 'error'
        if (res.statusCode === 200) {
          type = 'success'
          this.temp.Avatar = res.data
        }

        TipsBox(type, res.message)
      })
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9 !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 70px;
  height: 70px;
  line-height: 70px;
  text-align: center;
}
.avatar {
  width: 70px;
  height: 70px;
  display: block;
}
</style>
